package client

import (
	"errors"
	"gitee.com/slh1992/plugin-sip/sip"
	"gitee.com/slh1992/plugin-sip/transaction"
)

type SipServer struct {
	*transaction.Core `json:"-"`
	sn                int
}

type SipServerHandleFunc interface {
	HandleRegister(req *sip.Request, tx *transaction.GBTx)
	HandleInvite(req *sip.Request, tx *transaction.GBTx)
	HandleMessage(req *sip.Request, tx *transaction.GBTx)
	HandleAck(req *sip.Request, tx *transaction.GBTx)
	HandleNotify(req *sip.Request, tx *transaction.GBTx)
	HandleByte(req *sip.Request, tx *transaction.GBTx)
}

func NewServer(config *transaction.Config) (*SipServer, error) {
	if config.SipIP == "" {
		return nil, errors.New("Sip公网地址不能为空！")
	}
	if config.SipPort == 0 {
		return nil, errors.New("Sip端口号未设置！")
	}
	if config.Serial == "" {
		return nil, errors.New("Sip序列不能为空！")
	}
	if config.Realm == "" {
		return nil, errors.New("Sip域不能为空！")
	}
	server := &SipServer{
		sn: 1,
	}
	s := transaction.NewCore(config)
	server.Core = s
	return server, nil
}

func (c *SipServer) SetUp(handle SipServerHandleFunc) error {
	c.RegistHandler(sip.REGISTER, handle.HandleRegister)
	c.RegistHandler(sip.INVITE, handle.HandleInvite)
	c.RegistHandler(sip.MESSAGE, handle.HandleMessage)
	c.RegistHandler(sip.NOTIFY, handle.HandleNotify)
	c.RegistHandler(sip.ACK, handle.HandleAck)
	c.RegistHandler(sip.BYE, handle.HandleByte)
	return c.StartAndWait()
}
